import socket
import json
import datetime
import threading


def handle_client_request(ip_port, new_client):
    print("客户端的id是", ip_port)
    while True:
        recv_data = new_client.recv(1024)
        # 对二进制数据进行解码变成字符串
        recv_content = recv_data.decode("utf-8")
        recv_content = json.loads(recv_content)
        print("接收客户端的数据为:", recv_content)
        if recv_content["说"] == "close":
            print("下线了")
            break
        # 获取当前系统的时间
        dict1 = {}
        time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        data_res = input(f"服务端:{time}")
        dict1["姓名"] = "服务器"
        dict1["时间"] = time
        dict1["说"] = data_res
        # 将数据进行编码
        data_res = json.dumps(dict1)
        # 发送数据到客户端
        new_client.send(data_res.encode("utf-8"))
    # 关闭服务端和客户端的套接字,表示和客户端停止通信
    new_client.close()


if __name__ == '__main__':
    # 1.创建tcp服务端套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 防止端口被占用
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 2.绑定端口号

    tcp_server_socket.bind(("", 9090))
    # 3.设置监听

    tcp_server_socket.listen(128)

    # 收发信息都使用新的套接字
    while True:
        # 4.等待接收客户端的连接请求
        new_client, ip_port = tcp_server_socket.accept()
        # 5.接收客户端数据
        sub_thread = threading.Thread(target=handle_client_request, args=(ip_port, new_client))
        # 设置守护主线程,主线程退出,子线程销毁
        sub_thread.setDaemon(True)
        # 启动子线程执行对应的任务
        sub_thread.start()
    # 7.关闭服务端套接字,表示不再等待接收客户端的连接请求
    tcp_server_socket.close()
